// store/modules/user.js

import axios from "axios";

// 将 API 基础 URL 提取到环境变量或配置文件中
const API_BASE_URL = "http://8.155.162.119/api";

const state = {
  user: JSON.parse(localStorage.getItem("user")) || null, // 从 localStorage 加载用户信息
  permissions: JSON.parse(localStorage.getItem("permissions")) || [], // 从 localStorage 加载权限
};

const mutations = {
  SET_USER(state, user) {
    state.user = user;
    localStorage.setItem("user", JSON.stringify(user)); // 同步到 localStorage
  },
  SET_PERMISSIONS(state, permissions) {
    state.permissions = permissions;
    localStorage.setItem("permissions", JSON.stringify(permissions)); // 同步到 localStorage
  },
  LOGOUT(state) {
    state.user = null;
    state.permissions = [];
    localStorage.removeItem("user"); // 移除用户信息
    localStorage.removeItem("permissions"); // 移除权限
  },
};

const actions = {
  async login({ commit }, { username, password }) {
    try {
      const response = await axios.get(`${API_BASE_URL}/operator/login`, {
        params:{
          operatorUsername: username,
          operatorPassword: password,
        }
      });

      // 检查响应数据是否存在
      if (!response.data || !response.data.data) {
        throw new Error('无效的服务器响应');
      }

      const data = response.data.data;
      const user = {
        id: data.operatorId,
        username: data.operatorUsername,
        role: data.operatorRole,
      };

      let permissions = [];
      if (data.operatorRole === "superadmin") {
        permissions = [
          "view_cardManagementView",
          "view_accountManagementView",
          "view_publicizeManagementView",
        ];
      } else {
        permissions = [
          "view_accountManagementView",
          "view_publicizeManagementView",
        ];
      }

      // 提交到 Vuex
      commit("SET_USER", user);
      commit("SET_PERMISSIONS", permissions);

      return { user, permissions };
    } catch (error) {
      // 更具体的错误处理
      if (error.response) {
        // 服务器有响应但状态码不在2xx范围内
        if (error.response.status === 401) {
          throw new Error('账户或密码错误，登录失败');
        } else {
          throw new Error(`登录失败，状态码：${error.response.status}`);
        }
      } else if (error.request) {
        // 请求已发出但没有响应
        throw new Error('网络错误，请检查您的网络连接');
      } else {
        // 其他错误
        throw new Error(`登录失败：${error.message}`);
      }
    }
  },

  logout({ commit }) {
    commit("LOGOUT");
  },
};

const getters = {
  user: (state) => state.user,
  permissions: (state) => state.permissions,
};

export default {
  namespaced: true, // 启用命名空间
  state,
  mutations,
  actions,
  getters,
};
